﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace ImageWater
{
    public partial class FormMain : Form
    {
        InitFile init = new InitFile();
        MsSqlHelper mssql = new MsSqlHelper();
        ImageWater iw = new ImageWater();

        DataTable dt = new DataTable();

        private delegate void DelSetPro(int pro, ProgressBar proBar);//设置进度条进度的委托方法

        public FormMain()
        {
            InitializeComponent();
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            if (folderBrowserDialog2.ShowDialog() == DialogResult.OK)
            {
                txtSave.Text = folderBrowserDialog2.SelectedPath;
            }
        }

        private void btnCreate_Click(object sender, EventArgs e)
        {
            int resi=0, reti=0, sron=0;
            GetImageDown(ref resi, ref reti, ref sron);
            MessageBox.Show("本批次应打水印" + resi.ToString() + "\r\n获取图片：" + reti.ToString() + "\r\n实际打水印：" + sron.ToString());
        }

        private void FormMain_Load(object sender, EventArgs e)
        {
            folderBrowserDialog2.SelectedPath = "F:\\tupian\\";
            txtSave.Text = "F:\\tupian\\";
            dataGridView1.Columns.Add(new DataGridViewTextBoxColumn() { Name = "imageid", HeaderText = "ID", DataPropertyName = "imageid" });
            dataGridView1.Columns.Add(new DataGridViewTextBoxColumn() { Name = "url", HeaderText = "地址", DataPropertyName = "url" });
            dataGridView1.ReadOnly = true;
            dataGridView1.AllowUserToAddRows = false;
            if (init.isauto)
            {
                btnStart.Enabled = false;
                btnStart_Click(sender, e);
            }
        }

        private void btnResult_Click(object sender, EventArgs e)
        {
            GetDataList();
            dataGridView1.DataSource = dt;
            dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
            dataGridView1.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);
            progressBar1.Value = 0;
        }

        /// <summary>
        /// 设置ProgressBar的进度。
        /// </summary>
        /// <param name="pro"></param>
        /// <param name="proBar"></param>
        private void SetProgressMessage(int pro, ProgressBar proBar)
        {
            //如果当前调用方不是创建控件的一方，则需要使用this.Invoke()
            //在这里，ProgressBar控件是由主线程创建的，所以子线程要对该控件进行操作
            //必须执行this.InvokeRequired进行判断。
            if (this.InvokeRequired)
            {
                DelSetPro setPro = new DelSetPro(SetProgressMessage);
                this.Invoke(setPro, new object[] { pro, proBar });
            }
            else
            {
                proBar.Value = Convert.ToInt32(pro);
            }
        }
        int s = 0;
        private void timer1_Tick(object sender, EventArgs e)
        {
            s++;
            textBox1.Text = s.ToString();
            if (!bW.IsBusy)
            {
                timer1.Enabled = false;
                bW.RunWorkerAsync();
            }
        }

        private void GetDataList() 
        {
            int count = int.Parse(txtGetCount.Text);
            string sql = "";
            /*
            if (checkBox1.Checked)
            {
                sql = "select top " + count + " rtrim(imageid) as imageid,'http://khoa.scjrm.com:86/'+url as url from ImageDoc(nolock) "
                    + " where leibie='检验报告' and isnull(pici,'')='' "
                    + " and exists(select 1 from spls_ck b(nolock) where b.spid=detailid and b.rq>=convert(varchar(10),getdate()-1,120) and b.pihao=fzxx1)  "
                +" order by imageid desc ";
            }
            else
            {
                sql = "select top " + count + " rtrim(imageid) as imageid,'http://khoa.scjrm.com:86/'+url as url from ImageDoc(nolock) "
                    + " where leibie='检验报告' and isnull(pici,'')='' "
                    + " and exists(select 1 from spls_ck b(nolock) where b.spid=detailid and b.rq>=convert(varchar(10),getdate()-1,120) and b.pihao=fzxx1)  "
                    +" order by imageid asc";
            }
             */
            try
            {
                sql = "select top " + count + " rtrim(imageid) as imageid,'http://khoa.scjrm.com:86'+url as url from ImageDoc(nolock) "
                        + " where isnull(pici,'')='' "
                        + " and  lastmodifytime>=getdate()-30 "
                        + " order by imageid " + (checkBox1.Checked ? "desc" : "asc");
                dt = mssql.ExecuteDt(sql);

            }
            catch (Exception ex)
            {
                init.WriteLog(ex.ToString(), true);
            }
        }


        private void GetImageDown(ref int resi, ref int reti, ref int sron)
        {
            try
            {
                resi = 0;
                reti = 0;
                sron = 0;
                string savefolder = txtSave.Text;
                //int count = dataGridView1.Rows.Count;
                int count = dt.Rows.Count;
                progressBar1.Maximum = count;

                for (int i = 0; i < count; i++)
                {
                    SetProgressMessage(i + 1, progressBar1);
                    resi++;
                    //string fileurl = dataGridView1.Rows[i].Cells["url"].Value.ToString();
                    string fileurl = dt.Rows[i]["url"].ToString();
                    string file = fileurl.Replace("http://khoa.scjrm.com:86/Upload", savefolder);
                    string patchfile = file.Substring(0, file.LastIndexOf("/"));
                    string imageid = dt.Rows[i]["imageid"].ToString();

                    if (!File.Exists(file))
                    {
                        System.Drawing.Image iSource = init.GetImage(fileurl);
                        if (iSource != null)
                        {
                            reti++;                            
                            bool flag = false;                           
                                flag = iw.AddWatermarkAndSave(patchfile, file, "", iSource, iSource.Height - 300, 10, Color.Red, new Font("宋体", 40));                            
                            if (flag)
                            {
                                sron++;
                                //string imageid = dataGridView1.Rows[i].Cells["imageid"].Value.ToString();                                
                                string sql = "update ImageDoc set pici='×' where imageid='" + imageid + "'";
                                mssql.ExecuteSql(sql);
                            }
                        }
                    }
                    else
                    {
                        string sql = "update ImageDoc set pici='×' where imageid='" + imageid + "'";
                        mssql.ExecuteSql(sql);
                        init.WriteLog("已存在："+file, false);
                    }
                    result=fileurl+":"+file;
                }
            }
            catch (Exception ex)
            {
                init.WriteLog(ex.ToString(), true);
            }
        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            int resi = 0, reti = 0, sron = 0,dtcount=0;
            GetDataList();
            dtcount = dt.Rows.Count;
            init.WriteLog(dtcount.ToString(), false);
            if (dtcount > 0)
            {
                GetImageDown(ref resi, ref reti, ref sron);
            }
        }

        private void bW_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            timer1.Enabled = true;
        }

        private void btnStart_Click(object sender, EventArgs e)
        {
            if (timer1.Enabled)
            {
                timer1.Enabled = false;
                btnStart.Enabled = true;
                btnStop.Enabled = false;
            }
            else
            {
                timer1.Enabled = true;
                btnStart.Enabled = false;
                btnStop.Enabled = true;
            }
        }
        string result = "";
        private void bW_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            string dt = DateTime.Now.ToString();
            string textresult = dt + "  " + result + "\r\n";
            textBoxResult.AppendText(textresult);
            textBoxResult.ScrollToCaret();
            
        }

        private void btnStop_Click(object sender, EventArgs e)
        {
            if (timer1.Enabled)
            {
                timer1.Enabled = false;
                btnStart.Enabled = true;
                btnStop.Enabled = false;
            }
        }

        private void FormMain_SizeChanged(object sender, EventArgs e)
        {
            //判断是否选择的是最小化按钮
            if (WindowState == FormWindowState.Minimized)
            {
                //隐藏任务栏区图标
                this.ShowInTaskbar = false;
                //图标显示在托盘区
                nIcon.Visible = true;
                nIcon.ShowBalloonTip(3, "系统信息", "【" + this.Text + "】已启动", ToolTipIcon.Info);
            }
            else
            {
                this.ShowInTaskbar = true;//任务栏
            }
        }

        private void FormMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (bW.IsBusy)
            {
                // 如果worker正在忙则应该取消本次关闭画面的动作  
                e.Cancel = true;
                // 等待worker关闭当前画面  
                bW.CancelAsync();
                this.Visible = false;
            }
        }

        private void nIcon_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            if (this.WindowState == FormWindowState.Minimized)
            {
                this.ShowInTaskbar = true;  //显示在系统任务栏
                this.WindowState = FormWindowState.Normal;  //还原窗体
            }
            this.WindowState = FormWindowState.Normal;
        }
    }
}

